import React, { Component } from "react"
import { Form, InputNumber, Input, Select, Button, message } from 'antd'
import constant from "../../finance-setting/loan-setting/constant"
import { deepFullCopy, messages } from "share/common"
import { Chooser } from "components/index"
import ExportService from './export-service'

const { Option } = Select;

@Form.create()
class ExportDetailRule extends Component{

  state = {
    saveLoading: false,
    sourceField: null,
    record: deepFullCopy(this.props.params.record)
  };

  componentDidMount() {
    const { record } = this.props.params;
    this.setState({
      sourceField: record.sourceFieldName ? [{fieldName: record.sourceFieldName, fieldCode: record.sourceFieldCode}] : null
    });
  }

  handleSave = () => {
    this.props.form.validateFieldsAndScroll((err, value) => {
      if (!err) {
        const { id } = this.props.params, { close } = this.props, { record } = this.state;
        this.setState({ saveLoading: true });
        if (value.sourceField && value.sourceField[0]) {
          value.sourceFieldName = value.sourceField[0].fieldName;
          value.sourceFieldCode = value.sourceField[0].fieldCode;
          delete value.sourceField;
        }
        let params = Object.assign(record, value);
        params.nachaTemplateId = id;
        value.fieldTypeCode && (params.fieldTypeName = this.option.find(item => item.key === value.fieldTypeCode).label);
        value.logicFieldCode && (params.logicFieldName = this.logicFieldOption.find(item => item.key === value.logicFieldCode).label);
        value.fieldFormatCode && (params.fieldFormatName = this.formatOption.concat(this.formatDateOption).concat(this.sequenceOption)
          .find(item => item.key === value.fieldFormatCode).label);
        ExportService.detailUpdate(params).then(() => {
          this.setState({ saveLoading: false }, () => {
            message.success(messages('common.operate.success')/*操作成功*/);
            close(true);
          });
        }).catch(e => {
          this.setState({ saveLoading: false });
          message.error(e.response.data.message)
        })
      }
    })
  };

  option = [
    { label: messages('finance-4.key382')/*来源字段*/, key: 'SOURCE' },
    { label: messages('finance-4.key383')/*固定字符*/, key: 'CONSTANT' },
    { label: messages('finance-4.key384')/*固定逻辑字段*/, key: 'LOGIC' }
  ];

  logicFieldOption = [
    { label: messages('finance-4.key385')/*是否跨行*/, key: 'INTERBANK' },
    { label: messages('finance-4.key386')/*是否对公*/, key: 'PUBLIC' },
    { label: messages('finance-4.key387')/*是否异地*/, key: 'OFFSITE' },
    { label: messages('finance-4.key427')/*序列号*/, key: 'SEQUENCE' }
  ];

  formatOption = [
    { label: '1/0', key: 'FORMAT_1' },
    { label: '0/1', key: 'FORMAT_2' },
    { label: messages('finance-4.key388')/*是/否*/, key: 'FORMAT_3' },
    { label: 'Y/N', key: 'FORMAT_4' }
  ];

  sequenceOption = [
    { label: messages('finance-4.key428')/*批次创建日期时分秒+4位流水*/, key: 'FORMAT_5' },
    { label: messages('finance-4.key429')/*自然数序列*/, key: 'FORMAT_6' }
  ];

  formatDateOption = [
    { label: 'yyyyMMdd', key: 'yyyyMMdd' },
    { label: 'yyyy-MM-dd', key: 'yyyy-MM-dd' },
    { label: 'yyyy/MM/dd', key: 'yyyy/MM/dd' }
  ];

  clear = () => {
    const { record } = this.state;
    this.props.form.setFieldsValue({
      sourceField: undefined,
      fieldFormatCode: undefined
    });
    record.fieldFormatCode = undefined;
    this.setState({ sourceField: null, record });
  };

  handleChangeSourceField = value => {
    const { record } = this.state;
    record.fieldFormatCode = undefined;
    this.setState({ sourceField: value, record });
  };

  clearFieldFormatCode = () => {
    this.props.form.setFieldsValue({
      fieldFormatCode: undefined
    })
  };

  render() {
    const { formItemLayout } = constant;
    const { saveLoading, sourceField, record } = this.state;
    const { close } = this.props;
    const { getFieldDecorator, getFieldValue } = this.props.form;
    let temp = getFieldValue('fieldTypeCode');
    return (
      <div>
        <Form className={'new-form'}>
          <Form.Item
            label={messages('common.sequence')/*序号*/}
            {...formItemLayout}
          >
            {getFieldDecorator('sequence', {
              rules: [
                { required: true, message: messages('common.please.input')/*请输入*/ }
              ],
              initialValue: record.sequence
            })(
              <InputNumber placeholder={messages('common.please.input')/*请输入*/} min={0}/>
            )}
          </Form.Item>
          <Form.Item
            label={messages('finance-4.key389')/*字段名称*/}
            {...formItemLayout}
          >
            {getFieldDecorator('fieldName', {
              rules: [
                { required: true, message: messages('common.please.input')/*请输入*/ }
              ],
              initialValue: record.fieldName
            })(
              <Input placeholder={messages('common.please.input')/*请输入*/}/>
            )}
          </Form.Item>
          <Form.Item
            label={messages('finance-4.key390')/*字段类型*/}
            {...formItemLayout}
          >
            {getFieldDecorator('fieldTypeCode', {
              rules: [
                { required: true, message: messages('common.select')/*请选择*/ }
              ],
              initialValue: record.fieldTypeCode
            })(
              <Select placeholder={messages('common.select')/*请选择*/} onChange={this.clear}>
                {this.option.map(item => <Option key={item.key}>{item.label}</Option>)}
              </Select>
            )}
          </Form.Item>
          {temp === 'SOURCE' && (
            <div>
              <Form.Item
                label={messages('finance-4.key391')/*来源字段名称*/}
                {...formItemLayout}
              >
                {getFieldDecorator('sourceField', {
                  rules: [
                    { required: true, message: messages('common.select')/*请选择*/ }
                  ],
                  initialValue: record.sourceFieldName ? [{fieldName: record.sourceFieldName, fieldCode: record.sourceFieldCode}] : undefined
                })(
                  <Chooser
                    selectorItem={{
                      title: messages('finance-4.key392')/*选择映射字段编码*/,
                      url: `/payment/api/nachaTemplate/field/mapping/findPage`,
                      searchForm: [{
                        type: 'input', id: 'keyword', label: messages('finance-4.key393')/*映射字段编码/名称*/
                      }],
                      columns: [{
                        title: messages('finance-4.key394')/*映射字段编码*/, dataIndex: 'fieldCode'
                      }, {
                        title: messages('finance-4.key395')/*映射字段名称*/, dataIndex: 'fieldName'
                      }],
                      key: 'fieldCode'
                    }}
                    onChange={this.handleChangeSourceField}
                    valueKey="fieldCode"
                    labelKey="fieldName"
                    single
                  />
                )}
              </Form.Item>
            </div>
          )}
          {temp === 'LOGIC' && (
            <div>
              <Form.Item
                label={messages('finance-4.key396')/*逻辑字段*/}
                {...formItemLayout}
              >
                {getFieldDecorator('logicFieldCode', {
                  rules: [
                    { required: true, message: messages('common.select')/*请选择*/ }
                  ],
                  initialValue: record.logicFieldCode
                })(
                  <Select placeholder={messages('common.select')/*请选择*/} onChange={this.clearFieldFormatCode}>
                    {this.logicFieldOption.map(item => <Option key={item.key}>{item.label}</Option>)}
                  </Select>
                )}
              </Form.Item>
              <Form.Item
                label={messages('finance-4.key397')/*字段格式*/}
                {...formItemLayout}
              >
                {getFieldDecorator('fieldFormatCode', {
                  rules: [
                    { required: true, message: messages('common.select')/*请选择*/ }
                  ],
                  initialValue: record.fieldFormatCode
                })(
                  <Select placeholder={messages('common.select')/*请选择*/}>
                    {this[getFieldValue('logicFieldCode') === 'SEQUENCE' ? 'sequenceOption' : 'formatOption']
                      .map(item => <Option key={item.key}>{item.label}</Option>)}
                  </Select>
                )}
              </Form.Item>
            </div>
          )}
          {sourceField && (sourceField[0].isDate || record.fieldFormatCode) && (
            <Form.Item
              label={messages('finance-4.key397')/*字段格式*/}
              {...formItemLayout}
            >
              {getFieldDecorator('fieldFormatCode', {
                rules: [
                  { required: true, message: messages('common.select')/*请选择*/ }
                ],
                initialValue: record.fieldFormatCode
              })(
                <Select placeholder={messages('common.select')/*请选择*/}>
                  {this.formatDateOption.map(item => <Option key={item.key}>{item.label}</Option>)}
                </Select>
              )}
            </Form.Item>
          )}
          {temp === 'CONSTANT' && (
            <Form.Item
              label={messages('finance-4.key383')/*固定字符*/}
              {...formItemLayout}
            >
              {getFieldDecorator('fieldValue', {
                initialValue: record.fieldValue
              })(
                <Input placeholder={messages('common.please.input')/*请输入*/}/>
              )}
              <div>{messages('finance-4.key430')/*如果启用了编码规则定义，请尝试避免表单编码、公司编码、人员工号、编码规则定义内的固定字符之间相同的情况*/}</div>
            </Form.Item>
            )}
          <div className='slide-footer'>
            <Button type='primary' onClick={this.handleSave} loading={saveLoading}>{messages('common.ok')/*确定*/}</Button>
            <Button onClick={() => close()}>{messages('common.cancel')/*取消*/}</Button>
          </div>
        </Form>
      </div>
    )
  }

}

export default ExportDetailRule
